package com.roubsite.admin.utils;

import com.roubsite.admin.bean.RsUsers;
import com.roubsite.admin.dao.user.IUserDao;
import com.roubsite.database.dao.DataSet;
import com.roubsite.database.dao.EntityDao;
import com.roubsite.security.utils.RSPasswordUtil;

public class UserUtils {
	private IUserDao user;

	public static final int REGISTER_SUCCESS = 1, REGISTER_ERROR_USER_NAME_IS_USED = -1,
			REGISTER_ERROR_USER_NAME_TOO_LONG = -2, REGISTER_ERROR = 0, CHANGE_PASS_OK = 1,
			CHANGE_PASS_NEW_NEW1_NEQ = -1, CHANGE_PASS_OLDPASS_ERR = -2, CHANGE_PASS_NO_USER = -3;

	public UserUtils(IUserDao userDao) {
		this.user = userDao;
	}

	public int register(String userId, String username, String password, String roleId, String organId) {
		if (this.user.isInSystem(username)) {
			return REGISTER_ERROR_USER_NAME_IS_USED;
		}
		if (username.length() > 1024) {
			return REGISTER_ERROR_USER_NAME_TOO_LONG;
		}
		password = new RSPasswordUtil().encode(password);
		try {
			user.register(userId, username, password, roleId, organId);
			return REGISTER_SUCCESS;
		} catch (Exception e) {
			EntityDao.log.error("添加用户失败", e);
			return REGISTER_ERROR;
		}
	}

	/**
	 * 修改用户密码方法
	 * 
	 * @param uid      用户id
	 * @param oldPass  老密码（明文）
	 * @param newPass  新密码（明文）
	 * @param newPass2 确认新密码（明文）
	 * @return
	 */
	public int changePassword(String uid, String oldPass, String newPass, String newPass2) {
		DataSet userInfo = user.getUserInfoById(uid);
		if (userInfo.getCount() > 0) {
			String password = ((RsUsers) userInfo.getRows().get(0)).getUserPassword();
			RSPasswordUtil passUtils = new RSPasswordUtil();
			if (passUtils.matches(oldPass, password)) {
				if (newPass.equals(newPass2)) {
					user.updatePassword(passUtils.encode(newPass), uid);
					return CHANGE_PASS_OK;
				} else {
					return CHANGE_PASS_NEW_NEW1_NEQ;
				}
			} else {
				return CHANGE_PASS_OLDPASS_ERR;
			}
		} else {
			return CHANGE_PASS_NO_USER;
		}
	}

}